const { getHtml } = require('./utils/http')
const db = require('./utils/datebase')
const log = require('./utils/log')
let pageIndex = 0
let config = {}
const getList = async (url, content) => {
    pageIndex ++
    let $ = await getHtml(url, 1000)
    if (pageIndex > config.pageLimit && config.isLimit) {
        log.i('爬取完成')
        pageIndex = 0
        return true
    }
    if (!$) {
        log.i('遇到错误：重启')
        return getList(url, content)
    }
    let urls = []
    $('.list.g-clear .item a').each((i, elem) => {
        urls.push('https://www.360kan.com' + $(elem).attr('href'))
    })
    for (let i = 0; i < urls.length; i++) {
        await getDetail(urls[i], content)
    } 
    log.i(`第${pageIndex}页爬取完毕`)
    let next = ''
    $('#js-ew-page a').each((i, elem) => {
        if ($(elem).text() == '下一页>') {
            next = $(elem).attr('href')
        }
    })
    if (next) {
        return getList(next,content)
    } else {
        log.i('爬取完成')
        return true
    }
}
const getDetail = async (url, {base_type} ) => {
    let filmID = 0
    let $ = await getHtml(url, 1000)
    if (!$) {
        log.i('遇到错误：跳过')
        return
    }
    let film = {
        base_type,
        name: $('.title-left h1').text().trim(),
        pic: $('.s-cover-img img').attr('src'),
        year: parseInt($($('.g-clear.item-wrap .item')[1]).text().replace('年代：', '')),
        updated_at: new Date()
    }
    if (!film.name) {
        log.i('名称不存在：跳过')
        return
    }
    let area_name = $($('.g-clear.item-wrap .item')[1]).text().replace('地区 ：', '');
    switch (area_name) {
        case '大陆':
            film.area_id=1
        break
        case '香港':
            film.area_id=2
        break
        case '台湾':
            film.area_id=3
        break
        case '美国':
            film.area_id=4
        break
        case '日本':
            film.area_id=5
        break
        case '韩国':
            film.area_id=6
        break
        case '泰国':
            film.area_id=7
        break
        case '新加坡':
            film.area_id=9
        break 
        case '英国':
            film.area_id=8
        break   
        default :
            film.area_id=99
        break
    }
    film.content_type = ''
    $('.cat.first').each((i, elem) => {
        if ($(elem).text() ) {
            film.content_type += $(elem).text().replace('undefined', '') + ',';
        }
    })
    for(var key in film){ // 删除无效值
        if (!film[key]) {
            delete film[key]
        }
    }
    let exist = await db.existsAndGet('vods',{name: film.name, base_type})
    if (exist) {
        filmID  = exist['id']
        film.id = filmID
        await db.update('vods', film)
        log.i(`成功更新：`+ film.name)
    } else {
        film.created_at = film.updated_at
        film.status = 0
        db.insert('vods', film)
        log.i(`插入成功：`+ film.name)
    }
    // let tabs = $('.num-tab-main.js-tab.g-clear')
    // let elements
    // if (tabs.length > 1) {
    //     elements = $(tabs[1]).find('a')
    // } else {
    //     elements = $(tabs[0]).find('a')
    // }
    // for (let i = 0; i<elements.length; i++) {
    //     let element = $(elements[i])
    //     let name = element.text().trim().replace('新', '')
    //     if (name == '收起' || name == '展开更多' || name == '......') {
    //         continue
    //     }
    //     let url = element.attr('href').replace('360kan.tv.free', 'www.filmsugar.com')
    //     let film_set = {
    //         name,
    //         url,
    //         type: 'link',
    //         vod_id: filmID,
    //         group_id: 2,
    //         updated_at: new Date()
    //     }
    //     let existSet = await db.existsAndGet('play_sets', {name: film_set.name, vod_id: film_set.vod_id, group_id: film_set.group_id})
    //     if (existSet) {
    //         film_set.id = existSet.id
    //         await db.update('play_sets', film_set)
    //     }
    // }
    // 爬取电影
    // if (elements.length === 0) {
    //     let film_set = {
    //         name: '在线播放',
    //         url: $('.top-list  .top-list-btns a').attr('href'),
    //         type: 'link',
    //         vod_id: filmID,
    //         group_id: 2
    //     }
    //     let existSet = await db.existsAndGet('play_sets', {vod_id: film_set.vod_id, group_id: film_set.group_id})
    //     if (existSet) {
    //         film_set.id = existSet.id
    //         await db.update('play_sets', film_set)
    //     } else {
    //         film_set.created_at = new Date()
    //         await db.insert('play_sets', film_set)
    //     }
    // }
 
    return
}
const initContentType  =  (url, base_type_id) => {
    getHtml(url)
    .then($ => {
        let list = $($('dd.g-clear.js-filter-content')[1]).find('.js-tongjip')
        // list = list
        list.each(async(i, elme) => {
            let contentType = {
                base_type_id,
                name: $(elme).text().trim()
            }
            await db.save('content_types', contentType)
        })
        return true
    })
}
const start = async(config) => {
    this.config = config
    await getList('https://www.360kan.com/dongman/list', {base_type: 'dongman'})
    await getList('https://www.360kan.com/dianying/list', {base_type: 'dianying'})
    await getList('https://www.360kan.com/zongyi/list', {base_type: 'dianying'})
    await getList('https://www.360kan.com/dianshi/list.php?rank=rankhot&cat=all&area=all&act=all&year=all&pageno=1', {base_type: 'dianshiju'})
}
module.exports = {
    start
}